package com.stony.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.stony.core.exception.ExcelParseException;

public class FeeExcelParser {

	private List results = new ArrayList();

	private List errorresults = new ArrayList();

	public void run(InputStream inputstream) {

		POIFSFileSystem fs = null;

		HSSFWorkbook wb = null;

		try {

			fs = new POIFSFileSystem(inputstream);

			wb = new HSSFWorkbook(fs);

		} catch (IOException e) {

			e.printStackTrace();

			throw new ExcelParseException();

		}

		HSSFSheet sheet = wb.getSheetAt(0);

		int lastRow = sheet.getLastRowNum();

		HSSFRow row1 = sheet.getRow(0);

		if (row1 == null) {
			errorresults.add("no row");
			return;
		}

		List cols1 = new ArrayList();

		for (short j = 3;; j++) {
			try {

				String str = (String) new ExcelType(ExcelType.CELL_TYPE_STRING,
						true).getCellValue(row1.getCell(j));

				String expenseno = str.substring(0, str.indexOf("|"));

				try {
					Long l = new Long(Long.parseLong(expenseno));
					cols1.add(l);
				} catch (NumberFormatException e) {
					errorresults.add("error:" + str);
					return;
				}

			} catch (Exception e) {
				break;
			}
		}

		results.add(cols1);

		for (int i = 1; i <= lastRow; i++) {

			HSSFRow row = sheet.getRow(i);

			if (row == null)
				continue;

			List cols = new ArrayList();

			cols.add(new ExcelType(ExcelType.CELL_TYPE_DATE, false).getCellValue(row.getCell((short)0)));
			
			for (short j = 1; j < 3; j++) {
				try {
					cols.add(new ExcelType(ExcelType.CELL_TYPE_STRING, false)
							.getCellValue(row.getCell(j)));

				} catch (Exception e) {
					errorresults.add("row[" + i + "],col[" + (j + 1) + "]"
							+ e.getMessage());
				}
			}

			for (short j = 3; j < cols1.size() + 3; j++) {
				try {
					cols.add(new ExcelType(ExcelType.CELL_TYPE_NUMERIC, false)
							.getCellValue(row.getCell(j)));

				} catch (Exception e) {
					errorresults.add("row[" + i + "],col[" + (j + 1) + "]"
							+ e.getMessage());
				}
			}

			results.add(cols);
		}

	}

	public List getErrorresults() {
		return errorresults;
	}

	public List getResults() {
		return results;
	}
}
